package com.totem.admin.schedule;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.totem.admin.mapper.TAppConfigItemMapper;
import com.totem.admin.mapper.TAppConfigMapper;
import com.totem.admin.mapper.TSubscribeDailyEndMapper;
import com.totem.admin.model.TSubscribeDailyEnd;
import com.totem.admin.service.ITSubscribeDailyEndService;
import com.totem.base.constants.CommonConstants;
import com.totem.base.enums.*;
import com.totem.base.util.DateUtils;
import com.totem.customer.mapper.TCustomerMapper;
import com.totem.customer.mapper.TInviteMapper;
import com.totem.customer.mapper.TMemberMapper;
import com.totem.customer.model.TCustomers;
import com.totem.customer.model.TInvite;
import com.totem.customer.model.TMembers;
import com.totem.customer.serivce.IMemberCommonService;
import com.totem.order.mapper.*;
import com.totem.order.model.TOrders;
import com.totem.order.model.TSubscribeOrderItems;
import com.totem.order.model.TWalletJournal;
import com.totem.order.model.TWallets;
import com.totem.order.service.*;
import com.totem.product.model.TSubscribe;
import com.totem.product.service.ITSubscribeService;
import com.totem.startup.InitialGlobalConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SubscribeDailyTask {
    @Autowired
    private TCustomerMapper tCustomerMapper;
    @Autowired
    private TWalletMapper tWalletMapper;
    @Autowired
    private ITWalletService itWalletService;
    @Autowired
    private TWalletJournalMapper tWalletJournalMapper;
    @Autowired
    private ITWalletJournalService itWalletJournalService;
    @Autowired
    private TInviteMapper tInviteMapper;
    @Autowired
    private TMemberMapper tMemberMapper;
    @Autowired
    private TOrderMapper tOrderMapper;
    @Autowired
    private ITOrderService itOrderService;
    @Autowired
    private TSubscribeOrderItemMapper subscribeOrderItemMapper;
    @Autowired
    private ITSubscribeOrderItemService itSubscribeOrderItemService;
    @Autowired
    private TSubscribeDailyEndMapper tSubscribeDailyEndMapper;
    @Autowired
    private ITSubscribeDailyEndService itSubscribeDailyEndService;
    @Autowired
    private ITSubscribeService itSubscribeService;
    @Autowired
    private TAppConfigMapper tAppConfigMapper;
    @Autowired
    private TAppConfigItemMapper tAppConfigItemMapper;
    @Autowired
    private TSubscribeOrderItemMapper tSubscribeOrderItemMapper;
    @Autowired
    private IMemberCommonService iMemberCommonService;
    @Autowired
    private SubscribeAwardTask subscribeAwardTask;
    private final InitialGlobalConfig globalConfig = InitialGlobalConfig.instance();

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void daylightCancel(){
        List<TSubscribe> subscribeList = itSubscribeService.list();
        if(CollectionUtils.isEmpty(subscribeList)){
            log.error("未找到认购包配置");
            return;
        }

        LambdaQueryWrapper<TOrders> queryOrder = new LambdaQueryWrapper<>();
        queryOrder.eq(TOrders::getState, StateEnum.NORMAL.getCode());
        queryOrder.eq(TOrders::getOrderType, OrderTypeEnum.SUBSCRIBE.getCode());
        queryOrder.in(TOrders::getPaymentState,PaymentStateEnum.UNPAID.getCode());
        List<TOrders> unpaidList = tOrderMapper.selectList(queryOrder);
        if(CollectionUtils.isEmpty(unpaidList)){
            log.warn("未找到未支付的认购单");
            return;
        }

        Date now = new Date();
        Map<Boolean, List<TOrders>> unpaidCancelMap = unpaidList.stream().collect(
                Collectors.groupingBy(o->{
                    Date cancelTime = DateUtils.getAddDate(o.getOrderTime(), Calendar.MINUTE, 30);
                    return now.compareTo(cancelTime)>=0;
                }));
        List<TOrders> cancelOrderList = unpaidCancelMap.get(true);

        // 未支付但已超时的订单需要取消
        if (!CollectionUtils.isEmpty(cancelOrderList)) {
            List<Long> unpaidCancelOrderIds = cancelOrderList.stream().map(TOrders::getId).toList();
            LambdaUpdateWrapper<TOrders> updateUnpaidCancel = new LambdaUpdateWrapper<>();
            updateUnpaidCancel.set(TOrders::getPaymentState, PaymentStateEnum.CANCEL.getCode());
            updateUnpaidCancel.set(TOrders::getCancelTime, now);
            updateUnpaidCancel.in(TOrders::getId, unpaidCancelOrderIds);
            tOrderMapper.update(updateUnpaidCancel);

            LambdaUpdateWrapper<TSubscribeOrderItems> updateItemCancel = new LambdaUpdateWrapper<>();
            updateItemCancel.set(TSubscribeOrderItems::getReturnHandleState, HandleStateEnum.CANCEL.getCode());
            updateItemCancel.in(TSubscribeOrderItems::getOrderId, unpaidCancelOrderIds);
            tSubscribeOrderItemMapper.update(updateItemCancel);
        }
    }

    // 最近一段时间处理了团队和奖励的是否可以升级,封号不影响
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void daylightPersonalInvestLevelCal(){
        LocalDateTime passed = LocalDateTime.now().minusDays(1);
        Date passDate = Date.from(passed.atZone(ZoneId.systemDefault()).toInstant());

        LambdaQueryWrapper<TSubscribeOrderItems> subscribeQuery = new LambdaQueryWrapper<>();
        subscribeQuery.gt(TSubscribeOrderItems::getUpdateTime, passDate);
        subscribeQuery.and(lambdaQueryWrapper->
                lambdaQueryWrapper.eq(TSubscribeOrderItems::getTeamHandleState, HandleStateEnum.HANDLED)
                        .or().eq(TSubscribeOrderItems::getTeamHandleState, HandleStateEnum.HANDLED));
        List<TSubscribeOrderItems> itemList = tSubscribeOrderItemMapper.selectList(subscribeQuery);
        List<Long> orderIdList = itemList.stream().map(TSubscribeOrderItems::getOrderId).toList();
        if(CollectionUtils.isEmpty(orderIdList)){
            log.warn("无可处理个人投入的认购单");
            return;
        }

        LambdaQueryWrapper<TWalletJournal> journalListQuery = new LambdaQueryWrapper<>();
        journalListQuery.in(TWalletJournal::getOrderId, orderIdList);
        journalListQuery.eq(TWalletJournal::getJournalType, JournalTypeEnum.SUBSCRIBE_ORDER.getCode());
        journalListQuery.eq(TWalletJournal::getJournalState, JournalStateEnum.FINISHED.getCode());
        journalListQuery.orderByDesc(TWalletJournal::getUpdateTime);
        List<TWalletJournal> journalList = tWalletJournalMapper.selectList(journalListQuery);
        List<Long> customerIdList = journalList.stream().map(TWalletJournal::getCustomerId).toList();

        customerIdList.forEach(custId->iMemberCommonService.calMemberLevel(custId));
    }

    // 计算所属团队的团队投入
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void daylightTeamInvestLevelCal(){
        List<TSubscribeOrderItems> unteamList = tSubscribeOrderItemMapper.findUnteam();
        if(CollectionUtils.isEmpty(unteamList)){
            log.warn("无新增业绩");
            return;
        }

        List<Long> orderIdList = unteamList.stream().map(TSubscribeOrderItems::getOrderId).toList();

        LambdaUpdateWrapper<TSubscribeOrderItems> updateItemWrapper = new LambdaUpdateWrapper<>();
        updateItemWrapper.set(TSubscribeOrderItems::getTeamHandleState, HandleStateEnum.HANDLING.getCode());
        updateItemWrapper.in(TSubscribeOrderItems::getOrderId, orderIdList);
        updateItemWrapper.eq(TSubscribeOrderItems::getTeamHandleState, HandleStateEnum.UNHANDLED.getCode());
        int effect = tSubscribeOrderItemMapper.update(updateItemWrapper);
        if(effect<=0){
            return;
        }

        LambdaQueryWrapper<TSubscribeOrderItems> queryHanding = new LambdaQueryWrapper<>();
        queryHanding.eq(TSubscribeOrderItems::getTeamHandleState, HandleStateEnum.HANDLING.getCode());
        List<TSubscribeOrderItems> handlingList = tSubscribeOrderItemMapper.selectList(queryHanding);
        if(CollectionUtils.isEmpty(handlingList)){
            log.warn("没有团队投入处理中的认购单");
            return;
        }
        List<Long> handlingIdList = handlingList.stream().map(TSubscribeOrderItems::getOrderId).toList();

        LambdaQueryWrapper<TWalletJournal> journalListQuery = new LambdaQueryWrapper<>();
        journalListQuery.in(TWalletJournal::getOrderId, handlingIdList);
        journalListQuery.eq(TWalletJournal::getJournalType, JournalTypeEnum.SUBSCRIBE_ORDER.getCode());
        journalListQuery.eq(TWalletJournal::getJournalState, JournalStateEnum.FINISHED.getCode());
        List<TWalletJournal> journalList = tWalletJournalMapper.selectList(journalListQuery);
        if(CollectionUtils.isEmpty(journalList)){
            log.warn("无新增业绩流水");
            return;
        }
        Set<Long> customerIdList = journalList.stream().map(TWalletJournal::getCustomerId).collect(Collectors.toSet());
        Map<Long, TSubscribeOrderItems> unteamMap = unteamList.stream().collect(Collectors.toMap(TSubscribeOrderItems::getOrderId, Function.identity()));

        LambdaQueryWrapper<TInvite> inviteQuery = new LambdaQueryWrapper<>();
        inviteQuery.in(TInvite::getInviteeId, customerIdList);
        List<TInvite> inviteList = tInviteMapper.selectList(inviteQuery);
        if(CollectionUtils.isEmpty(inviteList)){
            log.warn("无推荐人可增加业绩");

            journalList.forEach(journal->{
                TSubscribeOrderItems subscribeItem = unteamMap.get(journal.getOrderId());
                TSubscribeOrderItems updateItem = TSubscribeOrderItems.builder()
                        .id(subscribeItem.getId())
                        .teamHandleState(HandleStateEnum.HANDLED.getCode())
                        .build();
                tSubscribeOrderItemMapper.updateById(updateItem);
            });
            return;
        }

        // 有投入的客户的所有上级客户
        Map<Long, List<Long>> invitePathMap = inviteList.stream()
                .collect(Collectors.toMap(
                        TInvite::getInviteeId,
                        v-> Arrays.stream(v.getPath().split(",")).map(Long::valueOf).toList()));

        journalList.forEach(journal->{
            Long customerId = journal.getCustomerId();
            TSubscribeOrderItems subscribeItem = unteamMap.get(journal.getOrderId());
            List<Long> parentIdList = invitePathMap.get(customerId);

            if(!CollectionUtils.isEmpty(parentIdList)) {
                List<TMembers> memberList = tMemberMapper.selectBatchIds(parentIdList);
                iMemberCommonService.onSubscribePayment(journal, memberList, parentIdList);
            }

            TSubscribeOrderItems updateItem = TSubscribeOrderItems.builder()
                    .id(subscribeItem.getId())
                    .teamHandleState(HandleStateEnum.HANDLED.getCode())
                    .build();
            tSubscribeOrderItemMapper.updateById(updateItem);
        });
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void dayendReturn(){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime yesterday = now.minusDays(1);
        LocalDateTime tomorrow = now.plusDays(1);
        ZoneId sd = ZoneId.systemDefault();
        Date nowDate = Date.from(yesterday.atZone(sd).toInstant());
        Date yesterdayDate = Date.from(yesterday.atZone(sd).toInstant());
        Date tomorrowDate = Date.from(tomorrow.atZone(sd).toInstant());

        List<TSubscribe> subscribeList = itSubscribeService.list();
        if(CollectionUtils.isEmpty(subscribeList)){
            log.warn("未找到认购包配置");
            return;
        }
        Map<String, TSubscribe> subscribeMap = subscribeList.stream().collect(Collectors.toMap(TSubscribe::getSubscribeName, Function.identity()));

        LambdaQueryWrapper<TOrders> queryOrder = new LambdaQueryWrapper<>();
        queryOrder.eq(TOrders::getState, StateEnum.NORMAL.getCode());
        queryOrder.eq(TOrders::getOrderType, OrderTypeEnum.SUBSCRIBE.getCode());
        queryOrder.in(TOrders::getPaymentState, PaymentStateEnum.FINISHED.getCode());
        List<TOrders> orderList = tOrderMapper.selectList(queryOrder);
        if(CollectionUtils.isEmpty(orderList)){
            log.warn("未找到已完成的认购订单");
            return;
        }
        List<Long> finishedIdList = orderList.stream().map(TOrders::getId).toList();

        LambdaQueryWrapper<TSubscribeOrderItems> queryOrderItem = new LambdaQueryWrapper<>();
        queryOrderItem.in(TSubscribeOrderItems::getOrderId, finishedIdList);
        queryOrderItem.eq(TSubscribeOrderItems::getReturnHandleState, HandleStateEnum.HANDLING.getCode());
        List<TSubscribeOrderItems> finishedItemList = subscribeOrderItemMapper.selectList(queryOrderItem);
        if(CollectionUtils.isEmpty(finishedItemList)){
            log.warn("未找到未关闭的认购订单项");
            return;
        }

        QueryWrapper<TSubscribeDailyEnd> countDayend = new QueryWrapper<>();
        countDayend.select("order_id, count(*) as count")
                .in("order_id", finishedIdList)
                .groupBy("order_id");
        List<Map<String, Object>> sdeCountList = tSubscribeDailyEndMapper.selectMaps(countDayend);

        Map<Long, Long> sdeCountMap = new HashMap<>();
        sdeCountList.forEach(map->{
            Object orderIdObj = map.get("order_id");
            Object countObj = map.get("count");
            sdeCountMap.put(((BigInteger)orderIdObj).longValue(), (Long)countObj);
        });

        Map<Boolean, List<TSubscribeOrderItems>> orderItemDisableMap = finishedItemList.stream().collect(
                Collectors.groupingBy(soi->{
                    Long count = sdeCountMap.get(soi.getOrderId());
                    count=count==null?0:count;
                    TSubscribe tSubscribe = subscribeMap.get(soi.getSubscribeName());
                    return count>=tSubscribe.getSubscribeDays();
                }));

        List<TSubscribeOrderItems> closeOrderItemList = orderItemDisableMap.get(true);
        List<TSubscribeOrderItems> returnOrderItemList = orderItemDisableMap.get(false);

        // 已支付已超期的订单需要关闭
        if(!CollectionUtils.isEmpty(closeOrderItemList)) {
            List<Long> closedOrderIds = closeOrderItemList.stream().map(TSubscribeOrderItems::getOrderId).toList();
            List<Long> closedIds = closeOrderItemList.stream().map(TSubscribeOrderItems::getId).toList();
            LambdaUpdateWrapper<TOrders> updateDisable = new LambdaUpdateWrapper<>();
            updateDisable.set(TOrders::getPaymentState, PaymentStateEnum.DISABLED.getCode());
            updateDisable.in(TOrders::getId, closedOrderIds);
            tOrderMapper.update(updateDisable);

            LambdaUpdateWrapper<TSubscribeOrderItems> updateItem = new LambdaUpdateWrapper<>();
            updateItem.set(TSubscribeOrderItems::getReturnHandleState, HandleStateEnum.HANDLED.getCode());
            updateItem.in(TSubscribeOrderItems::getId, closedIds);
            tSubscribeOrderItemMapper.update(updateItem);

            List<TSubscribeDailyEnd> sdeList = tSubscribeDailyEndMapper.findLatest(closedOrderIds);

            List<Long> customerIdList = sdeList.stream().map(TSubscribeDailyEnd::getCustomerId).toList();
            if(!CollectionUtils.isEmpty(customerIdList)) {
                LambdaQueryWrapper<TWallets> walletQuery = new LambdaQueryWrapper<>();
                walletQuery.in(TWallets::getCustomerId, customerIdList);
                List<TWallets> wallets = tWalletMapper.selectList(walletQuery);
                Map<Long, TWallets> walletsMap = wallets.stream().collect(Collectors.toMap(TWallets::getCustomerId, Function.identity()));

                Map<Long, TSubscribeDailyEnd> sdeMap = sdeList.stream().collect(Collectors.toMap(TSubscribeDailyEnd::getOrderId, Function.identity()));
                List<TWalletJournal> closeJournalList = closeOrderItemList.stream().map(soi->{
                    TSubscribeDailyEnd sde = sdeMap.get(soi.getOrderId());

                    BigDecimal amount = BigDecimal.ZERO;
                    BigDecimal beforeBalance = BigDecimal.ZERO;
                    if(sde!=null) {
                        TWallets wallet = walletsMap.get(sde.getCustomerId());
                        amount = sde.getInvest().add(sde.getEarnings());
                        // 认购包产生的收益一定都是USDO
                        beforeBalance = wallet.getUsdo();
                    }
                    BigDecimal afterBalance = beforeBalance.add(amount);
                    TWalletJournal journal = TWalletJournal.builder()
                            .customerId(sde.getCustomerId())
                            .orderId(sde.getOrderId())
                            .journalType(JournalTypeEnum.SUBSCRIBE_RETURN.getCode())
                            .currency(CurrencyEnum.USDO.getCode())
                            .beforeBalance(beforeBalance)
                            .amount(amount)
                            .afterBalance(afterBalance)
                            .charges(BigDecimal.ZERO)
                            .direction(DirectionEnum.DEBIT.getCode())
                            .journalState(JournalStateEnum.FINISHED.getCode())
                            .remark("认购包收益")
                            .build();
                    return journal;
                }).toList();
                itWalletJournalService.saveBatch(closeJournalList);

                List<TWallets> closeWallets = closeJournalList.stream().map(journal->{
                    TWallets wallet = TWallets.builder()
                            .customerId(journal.getCustomerId())
                            .build();
                    // 认购包收益一定都是USDO
                    BigDecimal balance = journal.getAfterBalance();
                    wallet.setUsdo(balance);
                    return wallet;
                }).toList();
                itWalletService.updateBatchById(closeWallets);
            }
        }

        if(CollectionUtils.isEmpty(returnOrderItemList)) {
            log.warn("无收益中的认购包");
            return;
        }

        List<Long> returnIds = returnOrderItemList.stream().map(TSubscribeOrderItems::getOrderId).toList();
        Set<Long> returnCustomerIdSet = orderList.stream().filter(o->returnIds.contains(o.getId())).map(TOrders::getCustomerId).collect(Collectors.toSet());
        if(CollectionUtils.isEmpty(returnCustomerIdSet)){
            log.warn("无收益中的认购包");
            return;
        }
        LambdaQueryWrapper<TCustomers> custQuery = new LambdaQueryWrapper<>();
        custQuery.eq(TCustomers::getState, StateEnum.NORMAL.getCode());
        custQuery.in(TCustomers::getId, returnCustomerIdSet);
        List<TCustomers> returnNormalCustList = tCustomerMapper.selectList(custQuery);
        if(CollectionUtils.isEmpty(returnNormalCustList)){
            log.warn("无正常的有认购包收益的客户");
            return;
        }
        List<Long> returnNormalCustIdList = returnNormalCustList.stream().map(TCustomers::getId).toList();

        LambdaQueryWrapper<TWalletJournal> journalQuery = new LambdaQueryWrapper<>();
        journalQuery.in(TWalletJournal::getCustomerId, returnNormalCustIdList);
        journalQuery.in(TWalletJournal::getOrderId, returnIds);
        journalQuery.eq(TWalletJournal::getJournalType, JournalTypeEnum.SUBSCRIBE_ORDER.getCode());
        journalQuery.eq(TWalletJournal::getJournalState, JournalStateEnum.FINISHED.getCode());
        List<TWalletJournal> journalList = tWalletJournalMapper.selectList(journalQuery);
        if(CollectionUtils.isEmpty(journalList)){
            log.warn("未找到认购支付流水,请检查数据库");
            return;
        }
        List<Long> normalOrderIdList = journalList.stream().map(TWalletJournal::getOrderId).toList();

        List<TSubscribeOrderItems> normalReturnItemList = returnOrderItemList.stream().filter(item->normalOrderIdList.contains(item.getOrderId())).toList();

        Map<Long, TSubscribe> orderSubscribeMap = normalReturnItemList.stream().collect(Collectors.toMap(
                TSubscribeOrderItems::getOrderId, subscribe->subscribeMap.get(subscribe.getSubscribeName())));

        // 与基金不同,认购包是每单分别计算收益
        Set<Long> orderIds = orderSubscribeMap.keySet();
        Map<Long, TWalletJournal> walletJournalMap = journalList.stream().collect(Collectors.toMap(TWalletJournal::getOrderId, Function.identity()));


        String yesterDayStr = CommonConstants.DEFAULT_DATE_FORMATTER.format(yesterday);
        String beforeDayStr = CommonConstants.DEFAULT_DATE_FORMATTER.format(yesterday);
        final String finalYesterday = yesterDayStr;

        /*
        LambdaQueryWrapper<TSubscribeDailyEnd> subscribeDailyEndQuery = new LambdaQueryWrapper<>();
        subscribeDailyEndQuery.in(TSubscribeDailyEnd::getOrderId, orderIds);
        subscribeDailyEndQuery.eq(TSubscribeDailyEnd::getCutOffDay, beforeDayStr);
        List<TSubscribeDailyEnd> beforeDailyEndList = tSubscribeDailyEndMapper.selectList(subscribeDailyEndQuery);
        */
        List<TSubscribeDailyEnd> beforeDailyEndList = tSubscribeDailyEndMapper.findLatest(new ArrayList<>(orderIds));
        List<TSubscribeDailyEnd> yesterdayDailyEndList = beforeDailyEndList.stream().map(bde->{
            TSubscribe tSubscribe = orderSubscribeMap.get(bde.getOrderId());

            BigDecimal rate = tSubscribe.getDailyRateReturn();
            BigDecimal invest = bde.getInvest().add(bde.getEarnings());
            BigDecimal earnings = invest.multiply(rate).setScale(CommonConstants.DEFAULT_SCALE, RoundingMode.HALF_UP);
            BigDecimal accEarnings = bde.getAccEarnings().add(earnings);

            TSubscribeDailyEnd yde = TSubscribeDailyEnd.builder()
                    .customerId(bde.getCustomerId())
                    .orderId(bde.getOrderId())
                    .cutOffDay(finalYesterday)
                    .subscribeLevel(tSubscribe.getSubscribeLevel())
                    .invest(invest)
                    .earnings(earnings)
                    .accEarnings(accEarnings)
                    .build();
            return yde;
        }).toList();

        if(!CollectionUtils.isEmpty(yesterdayDailyEndList)) {
            itSubscribeDailyEndService.saveBatch(yesterdayDailyEndList);

            List<TSubscribeDailyEnd> normalList = yesterdayDailyEndList.stream().filter(de->SubscribeLevelEnum.isNormal(de.getSubscribeLevel())).toList();
            if(!CollectionUtils.isEmpty(normalList)) {
                subscribeAwardTask.subscribeReturnAward(normalList);
            }
        }

        List<Long> existsIds = beforeDailyEndList.stream().map(TSubscribeDailyEnd::getOrderId).toList();
        List<Long> newIds = orderIds.stream().filter(id->!existsIds.contains(id)).toList();
        List<TSubscribeDailyEnd> newOrderDailyEndList = newIds.stream().map(id->{
            TSubscribe tSubscribe = orderSubscribeMap.get(id);
            TWalletJournal journal = walletJournalMap.get(id);
            Long customerId = journal.getCustomerId();

            BigDecimal rate = tSubscribe.getDailyRateReturn();
            BigDecimal invest = journal.getAmount();
            BigDecimal earnings = invest.multiply(rate).setScale(CommonConstants.DEFAULT_SCALE, RoundingMode.HALF_UP);
            BigDecimal accEarnings = BigDecimal.ZERO.add(earnings);

            TSubscribeDailyEnd yde = TSubscribeDailyEnd.builder()
                    .customerId(customerId)
                    .orderId(id)
                    .cutOffDay(finalYesterday)
                    .subscribeLevel(tSubscribe.getSubscribeLevel())
                    .invest(invest)
                    .earnings(earnings)
                    .accEarnings(accEarnings)
                    .build();
            return yde;
        }).toList();

        if(!CollectionUtils.isEmpty(newOrderDailyEndList)) {
            itSubscribeDailyEndService.saveBatch(newOrderDailyEndList);

            // 特殊认购包的日收益不会被计算奖励
            List<TSubscribeDailyEnd> normalList = newOrderDailyEndList.stream().filter(de->SubscribeLevelEnum.isNormal(de.getSubscribeLevel())).toList();
            if(!CollectionUtils.isEmpty(normalList)) {
                subscribeAwardTask.subscribeReturnAward(normalList);
            }
        }
    }
}
